import React from 'react'
import {connect} from 'react-redux'
import action from "../store/action";
import {Form, Tabs, Button, Layout, Input, Menu, Select, Icon, Tree, List, Modal} from 'antd';
import Controller from "../component/Controller"
import FileForm from "../component/FileForm"
import ControllerFunReturn from '../component/ControllerFunReturn'
import {withRouter} from 'react-router-dom';
import Qs from 'qs'
import {fetchProjectFileTreeApi, delFileInfoApi, projectModuleListApi} from "../api/projectConfig"
import jQuery from 'jquery'
import 'ztree'
import VoDomain from "../component/VoDomain";
import {Config} from "../utils/Constants";
import Module from "../component/Module";
import ProjectInfo from "../component/ProjectInfo";
import TableGenConfig from "../component/TableGenConfig";
import {getProjectApi} from "../api/projectManager";
import MicroService from "../component/MicroService";  //加载ztree
const $ = jQuery;

const {Header, Sider, Content} = Layout;
const TabPane = Tabs.TabPane;
const confirm = Modal.confirm
const Option = Select.Option;

class ProjectConfig extends React.Component {

    ztreeIndex = 0;
    projectId = 0;
    packageType = 'Hierarchical';
    moduleId = 0;
    fileTree = null;
    rightClickNode; // 右击节点
    fileFormRef;
    openStats = {};
    state = {
        projectTree: [], // 树
        moduleList: [], // 模块列表
        collapsed: false,
        rightMenu: {left: '0px', top: '0px', display: 'none'},
        projectDetail: {},
        rightClickMicroId : 0,
    };

    controllerFunReturnPopPanel;
    modulePanel; // 模块管理
    projectInfo;
    tableGenConfig;
    microService; // 微服务

    /* panels tabs */
    constructor(props, context) {
        super(props, context);

        /** 面板 */
        const tabPanes = [];
        this.state = {
            ...this.state,
            activeKey: null,
            tabPanes,
        };

        let {location: {search}} = this.props,
            {projectId = 0} = Qs.parse(search.substr(1)) || {};

        this.projectId = projectId;

    }

    componentDidMount() {

        getProjectApi(this.projectId).then((res)=>{
            this.setState({...this.state, projectDetail: res.data.data});
        });

        this.fetchProjectFileTree();

        let that = this;
        $(document).bind("click", function (e) {
            that.setState({...that.state, rightMenu: {display: 'none'}})
        });

        this.fetchModuleList();
    }

    fetchProjectFileTree = () => {
        let fileTreeRet = fetchProjectFileTreeApi(this.projectId, this.packageType, this.moduleId);
        fileTreeRet.then((res) => {
            this.setState({...this.state, projectTree: eval(res.data.data)});
        })

    }

    fetchModuleList = () => {
        projectModuleListApi(this.projectId).then((res) => {

            var moduleList = [{id: 0, name: ' - ', showName: '显示全部'}, ...res.data.data];

            this.setState({...this.state, moduleList: moduleList});
        });
    }

    onChange = (activeKey) => {
        this.setState({...this.state, activeKey});
    }

    onEdit = (targetKey, action) => {
        this[action](targetKey);
    }

    remove = (targetKey) => {
        let activeKey = this.state.activeKey;

        let lastIndex;
        this.state.tabPanes.forEach((pane, i) => {
            if ('panel_' + pane.id === targetKey) {
                lastIndex = i - 1;
            }
        });
        const tabPanes = this.state.tabPanes.filter(pane => 'panel_' + pane.id !== targetKey);
        if (lastIndex >= 0 && activeKey === targetKey) {
            activeKey = 'panel_' + tabPanes[lastIndex].id;
        }
        this.setState({...this.state, tabPanes, activeKey});
    }


    addTab = (treeNode) => {

        const tabPanes = this.state.tabPanes;
        const activeKey = 'panel_' + treeNode.id;
        var noOpen = true;
        for (var i = 0; i < tabPanes.length; i++) {
            if (treeNode.id === tabPanes[i].id) {
                noOpen = false;
                break;
            }
        }
        if (noOpen) {
            tabPanes.push(treeNode);
            this.setState({...this.state, tabPanes, activeKey});
        }
    }

    removeSelectedFile = () => {

        // 判断不可删除文件
        if ('vo' == this.rightClickNode.fileType) {

            var ret = Config.VO_IGNORE.findIndex((element) => (element == this.rightClickNode.name.split('.')[0]))
            if (ret > -1) {
                Modal.error({
                    title: '错误提示',
                    content: '非自定义创建无法删除！',
                });
                return;
            }
        }


        var that = this;
        confirm({
            title: 'Are you sure delete 【'+this.rightClickNode.name+'】 file?',
            content: 'Some descriptions',
            okText: 'Yes',
            okType: 'danger',
            cancelText: 'No',
            onOk() {
                var newTreeData = [];
                for (var i = 0; i < that.state.projectTree.length; i++) {
                    if (that.state.projectTree[i].id != that.rightClickNode.id) {
                        newTreeData.push(that.state.projectTree[i]);
                    }
                }
                that.setState({...that.state, projectTree: newTreeData})
                delFileInfoApi(that.rightClickNode.fileId);
            },
            onCancel() {
                console.log('Cancel');
            },
        });


    }

    showAddFilePanel = () => {

        this.setState({...this.state, rightMenu: {display: 'none'}})

        this.fileFormRef.showFileFormPanel({fileType: this.rightClickNode.name}, (ret) => {
            if (ret === 'close') {

            } else if (ret == 'add' || ret == 'update') {
                // reload
                this.fetchProjectFileTree();

            }
        })

    }

    toggle = () => {
        this.setState({
            ...this.state,
            collapsed: !this.state.collapsed,
        });
    }

    /* form */
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
            }
        });
    }

    render() {

        let zNodes = this.state.projectTree;

        window.zNodes = zNodes;

        for (var i = 0; i < zNodes.length; i++) {

            var node = zNodes[i];
            var type = node.fileType;
            if (type === 'package') {
                node['icon'] = require("../static/images/package_obj.gif");
            } else if (type === 'folder') {
                node['icon'] = require("../static/images/source-folder.gif");
            } else {
                node['icon'] = require("../static/images/jcu_obj.gif");
            }

            // open status
            if (this.openStats[node.indentify]) {
                node.open = true;
            } else if (this.openStats[node.indentify] === false) {
                node.open = false;
            }

            zNodes[i] = node;
        }

        var setting = {
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onExpand: (event, treeId, treeNode) => {
                    // console.info('onExpand---' + JSON.stringify(this.openStats));
                    this.openStats[treeNode.indentify] = true;

                    this.setState({...this.state});
                },
                onCollapse: (event, treeId, treeNode) => {

                    // console.info('onCollapse---' + JSON.stringify(this.openStats));
                    this.openStats[treeNode.indentify] = false;

                    this.setState({...this.state});
                },
                onClick: (event, treeId, treeNode) => {

                    if (treeNode.fileType === 'package') {
                        this.openStats[treeNode.indentify] = true;
                    } else {
                        if(treeNode.getParentNode()) {
                            this.openStats[treeNode.getParentNode().indentify] = true;
                            this.addTab(treeNode);
                        }
                    }
                    this.setState({...this.state});
                },
                onRightClick: (event, treeId, treeNode) => { // 右键事件
                    // console.info('right click ' + JSON.stringify(treeNode));

                    if (treeNode) {
                        //if(treeNode.fileType === 'package')
                        {
                            this.rightClickNode = treeNode;
                            this.setState({
                                ...this.state,
                                rightClickMicroId: treeNode.microId,
                                rightMenu: {display: '', left: event.clientX + 'px', top: (event.clientY - 60) + 'px'}
                            })
                        }
                    }
                }
            }
        };

        this.fileTree = $.fn.zTree.init($(this.refs.ztree), setting, zNodes);
        const {projectDetail, rightClickMicroId} = this.state;
        document.title = projectDetail.name;

        return (
            <Layout>
                <Sider
                    width={300}
                    trigger={null}
                    collapsible
                    collapsed={this.state.collapsed}
                >
                    <div className="logo">{this.state.projectDetail.name}</div>


                    <div style={{background: 'white', overflow: 'auto', height: '100%', position: 'relative'}}>

                        <div className="ztree" ref="ztree" id={`ztree_${this.ztreeIndex++}`}></div>

                        <div className="right-menu-panel"
                             style={{padding: '10px', width: '240px', position: 'absolute', ...this.state.rightMenu}}>
                            <List
                                style={{backgroundColor: 'white'}}
                                size="small"
                                bordered
                            >
                                <List.Item><a onClick={this.showAddFilePanel}><Icon
                                    type="plus-circle"/>添加文件</a></List.Item>
                                <List.Item><a onClick={this.removeSelectedFile}><Icon
                                    type="close-circle"/>删除文件</a></List.Item>
                            </List>
                        </div>

                    </div>


                </Sider>
                <Layout>
                    <Header style={{background: '#fff', padding: 0}}>
                        <Icon
                            style={{float: 'left'}}
                            className="trigger"
                            type={this.state.collapsed ? 'menu-unfold' : 'menu-fold'}
                            onClick={this.toggle}
                        />
                        <div style={{paddingTop: '18px'}}>
                            {/* Package Presentation Flat/Hierarchical */}
                            <Select className={"ant-col-3"} onChange={(value) => {
                                this.packageType = value;
                                this.fetchProjectFileTree();
                            }} placeholder="Hierarchical">
                                <Option value="Flat">Flat</Option>
                                <Option value="Hierarchical">Hierarchical</Option>
                            </Select>

                            {/* 模块过滤 */}
                            <Select className={"ant-col-4"} onChange={(index) => {
                                let value = this.state.moduleList[index];
                                this.moduleId = value.id;
                                this.fetchProjectFileTree();
                            }} placeholder="选择模块">
                                {this.state.moduleList.map((vo, index) => <Option
                                    key={index}>{vo.name + '-' + vo.showName}</Option>)}
                            </Select>

                            {/* Project Module */}
                            <Button onClick={() => {
                                this.modulePanel.showModal((opre) => {
                                    console.info('oper' + opre);
                                    this.fetchModuleList();
                                });
                            }} className={"ant-col-2"}>模块管理</Button>

                            {/* Project Info */}
                            <Button onClick={() => {
                                this.projectInfo.showModal((opre) => {
                                    this.fetchProjectFileTree();
                                });
                            }} className={"ant-col-2"}>项目详情</Button>

                            {/* Project Info */}
                            <Button onClick={() => {
                                this.tableGenConfig.showModal((opre) => {
                                    // 重新获取 table 列表
                                });
                            }} className={"ant-col-2"}>数据库表配置</Button>

                            {/* micro service */
                                projectDetail.proType === 'micro'?
                                    <Button onClick={() => {
                                        this.microService.showModal((opre) => {
                                            // 重新获取 table 列表
                                        });
                                    }} className={"ant-col-2"}>+微服务</Button>
                                    :''
                            }



                        </div>
                    </Header>


                    <Content style={{margin: '24px 16px', padding: 24, background: '#fff', minHeight: 280}}>

                        {/* 标签 */}
                        <div>
                            <Tabs
                                hideAdd
                                onChange={this.onChange}
                                activeKey={this.state.activeKey}
                                type="editable-card"
                                onEdit={this.onEdit}
                            >
                                {this.state.tabPanes.map(pane =>
                                    <TabPane tab={pane.name} key={'panel_' + pane.id}>
                                        {pane.fileType === 'controller'
                                            ?
                                            <Controller controllerFunReturnPopPanel={this.controllerFunReturnPopPanel}
                                                        fileNode={pane} key={pane.id}></Controller>
                                            :
                                            (pane.fileType === 'vo'
                                                    ?
                                                    <VoDomain projectId={this.projectId} fileNode={pane}
                                                              key={pane.id}></VoDomain>
                                                    :
                                                    ''
                                            )
                                        }
                                    </TabPane>)}
                            </Tabs>
                        </div>
                    </Content>
                </Layout>

                {/* 添加文件弹出框 */}
                <FileForm key="k_fileForm" projectDetail={projectDetail} microId={rightClickMicroId} onRef={(ref) => {
                    this.fileFormRef = ref
                }}></FileForm>

                {/* 设置返回参数 */}
                <ControllerFunReturn projectId={this.projectId} key="controller_fun_return_key" onRef={(ref) => {
                    this.controllerFunReturnPopPanel = ref
                }}></ControllerFunReturn>

                {/* 模块管理 */}
                <Module key="module" projectDetail={projectDetail} projectId={this.projectId} onRef={(ref) => {
                    this.modulePanel = ref
                }}></Module>

                {/* 项目详情 */}
                <ProjectInfo key="projectInfo" projectId={this.projectId} onRef={(ref) => {
                    this.projectInfo = ref
                }}></ProjectInfo>

                {/* 设置自动生成table */}
                <TableGenConfig key="tableGenConfig" projectId={this.projectId} onRef={(ref) => {
                    this.tableGenConfig = ref
                }}></TableGenConfig>

                {/* 微服务管理 */
                    projectDetail.proType === 'micro' ?
                        <MicroService key="MicroService" projectDetail={projectDetail} projectId={this.projectId}
                                      onRef={(ref) => {
                                          this.microService = ref
                                      }}></MicroService>
                        :''
                }

            </Layout>
        );
    }
}

const _ProjectConfig = Form.create()(ProjectConfig);
const __ProjectConfig = withRouter(connect(state => ({...state.projectConfig}), action.projectConfig)(_ProjectConfig))

export default __ProjectConfig;
